#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//锁
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//条件变量
void *active(void *args)
{
    std::string name=static_cast<char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        std::cout<<name.c_str()<<std::endl;
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

// int main()
// {
//     void *(*routine)(void *) = active;

//     pthread_t tid1,tid2,tid3;
//     pthread_create(&tid1,nullptr,active,(void*)"1");
//     pthread_create(&tid2,nullptr,active,(void*)"2");
//     pthread_create(&tid3,nullptr,active,(void*)"3");
//     printf("main thread ctrl begin");
//     while(true){
//         printf("wakeup newthread\n");
//         pthread_cond_signal(&cond);
//         sleep(1);
//     }

//     pthread_join(tid1, nullptr);
//     pthread_join(tid2, nullptr);
//     pthread_join(tid3, nullptr);
//     return 0;
// }

//结果:打印的时候是"1,2,3"地按顺序输出,由此可见线程在条件变量的指导下在cond内部排队
// 所以说cond内部有条件变量在排队

int main()
{
    void *(*routine)(void *) = active;

    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,nullptr,active,(void*)"1");
    pthread_create(&tid2,nullptr,active,(void*)"2");
    pthread_create(&tid3,nullptr,active,(void*)"3");
    printf("main thread ctrl begin");
    while(true){
        printf("wakeup newthread\n");
        pthread_cond_broadcast(&cond);
        sleep(1);
    }
    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);

    return 0;
} 